﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using JM.JCY.BusinessEntity;
using JM.JCY.Proxy;
using System.Data;
using Microsoft.SharePoint;
using JM.JCY.Common;
using System.Collections.Generic;

namespace JM.JCY.SharePointComponent.UserManagement.EditDept
{
    public partial class EditDeptUserControl : UserControl
    {
        static string JCYUrl = System.Configuration.ConfigurationManager.AppSettings["JCYUrl"].ToString();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                int selDeptId = -1;
                if (!String.IsNullOrEmpty(Request.QueryString["selDeptId"].ToString()))
                {
                    selDeptId = Int32.Parse(Request.QueryString["selDeptId"].ToString());
                    BindDataByDeptId(selDeptId);
                }
            }
        }

        private void BindDataByDeptId(int selDeptId)
        {

            GetDepartmentTitleByDeptId(selDeptId);
            DataSetUserManagement ds = new DataSetUserManagement();
            ds = (DataSetUserManagement)Session["DepartmentTitleDS"];
            if (ds.T_Department.Rows.Count > 0)
            {
                this.txtDeptName.Text = ds.T_Department[0].DeptName.ToString();
                this.hfDeptName.Value = this.txtDeptName.Text;
                this.txtDeptDescription.InnerText = ds.T_Department[0].DeptDesc.ToString();
            }

            DataSetUserManagement.T_JobTitleDataTable dt1 = new DataSetUserManagement.T_JobTitleDataTable();
            dt1 = ds.T_JobTitle;
            if (dt1.Rows.Count > 0)
            {
                box2View.DataSource = dt1;
                box2View.DataTextField = "JobTitle";
                box2View.DataValueField = "JobTitle";
                box2View.DataBind();
            }

            CodeTableDataSet.T_CodeTableDataTable dt2 = new CodeTableDataSet.T_CodeTableDataTable();
            dt2 = GetCodeTable(1, "JobTitle");

            foreach (DataRow dr1 in dt1.Rows)
            {
                for (int i = dt2.Count - 1; i >= 0; i--)
                {
                    if (dt2.Rows[i]["CodeDesc"].Equals(dr1["JobTitle"]))
                        dt2.Rows.RemoveAt(i);
                }
            }
            box1View.DataSource = dt2;
            box1View.DataTextField = "CodeDesc";
            box1View.DataValueField = "CodeDesc";
            box1View.DataBind();
        }

        private void GetDepartmentTitleByDeptId(int selDeptId)
        {
            DataSetUserManagement ds = new DataSetUserManagement();
            using (UserManagementProxy proxy = new UserManagementProxy())
            {
                ds = proxy.GetDepartmentTitleById(selDeptId);
            }
            Session["DepartmentTitleDS"] = ds.Copy();
        }

        protected void imgbtnSave_Click(object sender, ImageClickEventArgs e)
        {
            if (Page.IsValid)
            {
                SPWeb currentWeb = SPContext.Current.Web;
                string currentUserName = currentWeb.CurrentUser.Name.ToString();

                using (UserManagementProxy proxy = new UserManagementProxy())
                {

                    DataSetUserManagement dsUserMgr = new DataSetUserManagement();
                    dsUserMgr = (DataSetUserManagement)Session["DepartmentTitleDS"];
                    DataSetUserManagement.T_DepartmentDataTable dtUserMgr = dsUserMgr.T_Department;
                    DataSetUserManagement.T_JobTitleDataTable dtJobTitle = dsUserMgr.T_JobTitle;

                    for (int i = dtJobTitle.Count - 1; i >= 0; i--)
                    {
                        dtJobTitle[i].IsDeleted = true;
                    }


                    dtUserMgr[0].DeptName = this.txtDeptName.Text.Trim();
                    dtUserMgr[0].DeptDesc = this.txtDeptDescription.InnerText;
                    JCYUtility.UpdateCommonFields(dtUserMgr[0], currentUserName);



                    string s = Request.Form[box2View.UniqueID];
                    if (!string.IsNullOrEmpty(s))
                    {
                        foreach (var item in s.Split(','))
                        {
                            DataSetUserManagement.T_JobTitleRow drJobTitle = dtJobTitle.NewT_JobTitleRow();
                            drJobTitle.DeptId = dtUserMgr[0].ID;
                            drJobTitle.JobTitle = item.ToString();
                            drJobTitle.IsDeleted = false;
                            JCYUtility.UpdateCommonFields(drJobTitle, currentUserName);
                            dtJobTitle.Rows.Add(drJobTitle);
                        }
                    }

                    if (this.txtDeptName.Text != this.hfDeptName.Value)
                    {
                        EditDept(this.hfDeptName.Value, this.txtDeptName.Text, this.txtDeptDescription.InnerText, SPListTemplateType.DocumentLibrary);
                        EditDept(this.hfDeptName.Value + " 讨论版", this.txtDeptName.Text + " 讨论版", this.txtDeptDescription.InnerText, SPListTemplateType.DiscussionBoard);
                    }


                    proxy.CreateNewDepartment(dsUserMgr);
                    Session.Clear();
                }
                Response.Redirect("deptmgr.aspx");
            }
        }

        protected void imgbtnCancel_Click(object sender, ImageClickEventArgs e)
        {
            Session.Clear();
            Response.Redirect("deptmgr.aspx");
        }

        public CodeTableDataSet.T_CodeTableDataTable GetCodeTable(int applicationId, string codeCategory)
        {
            CodeTableDataSet.T_CodeTableDataTable dt = new CodeTableDataSet.T_CodeTableDataTable();
            using (CodeTableProxy proxy = new CodeTableProxy())
            {
                dt = proxy.GetCodeTable(applicationId, codeCategory);
            }
            return dt;
        }

        private void EditDept(string oldName, string newDocName, string newDocDesc, SPListTemplateType templateType)
        {
             SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(JCYUrl))
                {
                    using (SPWeb myWeb = site.AllWebs["MyDept"])
                    {
                        myWeb.AllowUnsafeUpdates = true;
                        myWeb.Lists.Add(newDocName, newDocDesc, templateType);
                        myWeb.Update();

                        // break permission from parent 
                        SPList newDoc = myWeb.Lists[newDocName];
                        if (!newDoc.HasUniqueRoleAssignments)
                            newDoc.BreakRoleInheritance(true);

                        SPRoleAssignmentCollection assignmentCol = newDoc.RoleAssignments;
                        for (int i = assignmentCol.Count - 1; i >= 0; i--)
                        {
                            assignmentCol.Remove(i);
                        }

                        // copy file from old to one
                        CopyFiles(oldName, newDocName);

                        // create group and set group owner
                        if (!IsExistGroup(newDocName))
                        {
                            SPMember member = myWeb.Author;
                            myWeb.SiteGroups.Add(newDocName, member, null, "Contributors to " + newDocName);
                        }

                        SPGroup newContribGroup = myWeb.SiteGroups[newDocName];
                        SPRoleDefinition contribRole = myWeb.RoleDefinitions.GetByType(SPRoleType.Contributor);
                        SPRoleAssignment contribRoleAssignment = new SPRoleAssignment(newContribGroup);
                        contribRoleAssignment.RoleDefinitionBindings.Add(contribRole);
                        newDoc.RoleAssignments.Add(contribRoleAssignment);

                        // copy users to new group

                        SPUserCollection users = myWeb.SiteGroups[oldName].Users;
                        SPGroup newGroup = myWeb.SiteGroups[newDocName];
                        foreach (SPUser user in users)
                        {
                            newGroup.Users.Add(user.LoginName, user.Email, user.Name, user.Notes);
                            newGroup.Update();
                        }

                        // delete old doc and old group
                        SPList oldDept = myWeb.Lists[oldName];

                        oldDept.BreakRoleInheritance(true);
                        SPRoleAssignmentCollection assignmentColOld = oldDept.RoleAssignments;
                        for (int i = assignmentColOld.Count - 1; i >= 0; i--)
                        {
                            assignmentColOld.Remove(i);
                        }
                        myWeb.SiteGroups.Remove(oldName);
                        myWeb.Lists.Delete(oldDept.ID);

                        myWeb.AllowUnsafeUpdates = false;

                   }
                }
            });
        }

        public bool IsExistGroup(string groupname)
        {
            bool exist = false;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {

                using (SPSite site = new SPSite(JCYUrl))
                {
                    using (SPWeb web = site.AllWebs[JCYConstant.SiteName.MyDept])
                    {

                        SPGroupCollection groups = web.SiteGroups;
                        foreach (SPGroup grouplist in groups) //判断组是否存在
                        {
                            if (grouplist.ToString().ToLower() == groupname.ToLower())
                                exist = true;
                        }
                    }
                }
            });

            return exist;


        }

        private void CopyFiles(string oldDoc, string newDoc)
        {

            SPWeb web = SPContext.Current.Web.Site.AllWebs["MyDept"];
            SPFileCollection collFile = web.GetFolder(oldDoc).Files;

            foreach (SPFile file in collFile)
            {
                file.CopyTo(newDoc + "/" + file.Name, true);

            }

        }
    }
}
